package com.ali.gts.service.impl;

import com.ali.gts.controller.EmpController;
import com.ali.gts.domain.GoodsDto;
import com.ali.gts.domain.SaleOrderDto;
import com.ali.gts.exception.NotEnougthException;
import com.ali.gts.mapper.GoodsMapper;
import com.ali.gts.mapper.SaleOrderMapper;
import com.ali.gts.service.BuyGoodService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class BuyGoodServiceImpl implements BuyGoodService{

    Logger logger = LoggerFactory.getLogger(BuyGoodServiceImpl.class);

    @Autowired(required = false)
    GoodsMapper goodsMapper;


    @Autowired(required = false)
    SaleOrderMapper saleOrderMapper;


    //@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = {NotEnougthException.class})
    //@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    @Override
    public void buyGoods(Integer goodsId, Integer num) {
        logger.info("====buy方法的开始====");
        //生成销售记录
        SaleOrderDto saleOrderDto = new SaleOrderDto();
        saleOrderDto.setGid(goodsId);
        saleOrderDto.setNum(num);
        saleOrderDto.setOrderId(UUID.randomUUID().toString());
        saleOrderMapper.insertSale(saleOrderDto);

        //查询商品
        GoodsDto goodsDto = goodsMapper.selectGoodsByGid(goodsId);
        if(goodsDto == null){
            throw  new NullPointerException(goodsId + "商品不存在");
        }else if(goodsDto.getAmount() < num){
            throw new NotEnougthException(goodsId + "库存不足");
        }


        //更新库存
        GoodsDto buyGoods = new GoodsDto();
        buyGoods.setGid(goodsId);
        buyGoods.setAmount(num);
        goodsMapper.updateGoods(buyGoods);
        logger.info("====buy方法的结束====");

    }
}
